package http

import (
	"context"
	comet "fgo/advance/other/discovery/bilibili/example/api/coment/grpc"
	"fgo/advance/other/discovery/bilibili/example/conf"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/keepalive"
	"net/http"
	"time"
)

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "hello world")
}
func TestDisconery(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "hello world")
}
func startServer(conf *conf.Config) {
	http.HandleFunc("/", IndexHandler)
	http.HandleFunc("/disconery", TestDisconery)
	if err := http.ListenAndServe(conf.HttpConfig.Addr, nil); err != nil {
		panic(err)
	}
}

// Server is comet server.
type Server struct {
	c      *conf.Config
	client comet.HelloClient
}

func NewServer(c *conf.Config) *Server {
	s := &Server{
		c: c,
	}
	s.client, _ = newCometClient("discovery://default/goim.test")
	go startServer(c)
	return s
}

// Close close the server.
func (s *Server) Close() (err error) {
	return
}

var (
	// grpc options
	grpcKeepAliveTime    = time.Duration(10) * time.Second
	grpcKeepAliveTimeout = time.Duration(3) * time.Second
	grpcBackoffMaxDelay  = time.Duration(3) * time.Second
	grpcMaxSendMsgSize   = 1 << 24
	grpcMaxCallMsgSize   = 1 << 24
)

const (
	// grpc options
	grpcInitialWindowSize     = 1 << 24
	grpcInitialConnWindowSize = 1 << 24
)

func newCometClient(addr string) (comet.HelloClient, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(time.Second))
	defer cancel()
	conn, err := grpc.DialContext(ctx, addr,
		[]grpc.DialOption{
			grpc.WithInsecure(),
			grpc.WithInitialWindowSize(grpcInitialWindowSize),
			grpc.WithInitialConnWindowSize(grpcInitialConnWindowSize),
			grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(grpcMaxCallMsgSize)),
			grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(grpcMaxSendMsgSize)),
			grpc.WithBackoffMaxDelay(grpcBackoffMaxDelay),
			grpc.WithKeepaliveParams(keepalive.ClientParameters{
				Time:                grpcKeepAliveTime,
				Timeout:             grpcKeepAliveTimeout,
				PermitWithoutStream: true,
			}),
		}...,
	)
	if err != nil {
		return nil, err
	}
	return comet.NewHelloClient(conn), err
}
